# coding=utf-8
# -*- coding: UTF-8 -*-
#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import time

from api import ApiInitializer
from ksai.config import app_config, VIEWS_FOLDER_NAME, STATIC_FOLDER_NAME, STATIC_URL_PREFIX
from ksai.context import ApplicationInitializer, Application
from ksai.events import EventsInitializer
from ksai.logger import setup_logging
from ksai.persistence import PersistenceInitializer
from ksai.threads import ThreadsInitializer
from ksai.utils.cli import is_database_command
from ksai.utils.paths import get_project_static_path, get_project_logs_path
from ksai.web.api import ApiEndpointInitializer
from ksai.web.resoruces import WebResourcesInitializer


def create_with_initializers(initializers: list[ApplicationInitializer] = None) -> Application:
    start_time = time.perf_counter()

    configs = app_config.model_dump()

    app = Application(
        __name__,
        template_folder=VIEWS_FOLDER_NAME,
        static_folder=STATIC_FOLDER_NAME,
        static_url_path=STATIC_URL_PREFIX,
    )

    # flask 2.2.5以下解决中文乱码问题
    app.config['JSON_AS_ASCII'] = False
    app.json.ensure_ascii = False
    app.config['STATIC_FOLDER'] = get_project_static_path()

    app.config.from_mapping(configs)

    logs_path = get_project_logs_path()
    setup_logging(app, logs_path)

    if initializers:
        for initializer in initializers:
            initializer.initialize(app)

    end_time = time.perf_counter()

    app.logger.info(f'Start app finished in {round(end_time - start_time, 2)} seconds')

    return app


def create_database_application() -> Application:
    from ksai.persistence.database import DatabaseMigrateInitializer, DatabasePersistenceInitializer
    return create_with_initializers([
        EventsInitializer(),
        DatabasePersistenceInitializer(),
        DatabaseMigrateInitializer(),
    ])


def create_web_application() -> Application:
    return create_with_initializers([
        EventsInitializer(),
        PersistenceInitializer(),
        ApiEndpointInitializer(),
        WebResourcesInitializer(),
        ApiInitializer(),
        ThreadsInitializer(),
    ])


def create_application() -> Application:
    if is_database_command():
        return create_database_application()
    return create_web_application()
